﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Data;
using System.Windows.Controls;

namespace Bonobo.Irc.Client.UI.Data
{
    // FIXME: turn into UserControl. also make internal sealed
    public sealed partial class IrcServerConversationTemplate : ResourceDictionary
    {
        public IrcServerConversationTemplate()
        {
            InitializeComponent();
        }

        public DataTemplate DataTemplate
        {
            get { return base["IrcServerConversationContentTemplate"] as DataTemplate; }
        }

        private void ConnectCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            var session = ((UIServerConversation)((Grid)sender).DataContext).Session;
            e.CanExecute = (session.State == IrcSessionState.Closed || session.State == IrcSessionState.Opening || session.State == IrcSessionState.ServerError);
        }

        private void ConnectExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var session = ((UIServerConversation)e.Parameter).Session;
            if (IsConnectionInfoValid((Grid)sender))
            {
                session.Open();
            }
        }

        private bool IsConnectionInfoValid(Grid sender)
        {
            var address = UpdateBinding("txtServerAddress", sender, TextBox.TextProperty);
            var port = UpdateBinding("txtPort", sender, TextBox.TextProperty);
            var username = UpdateBinding("txtUsername", sender, TextBox.TextProperty);
            var realname = UpdateBinding("txtFullName", sender, TextBox.TextProperty);

            return !address.HasError && !port.HasError && !username.HasError && !realname.HasError;
        }

        private BindingExpression UpdateBinding(String controlName, Grid sender, DependencyProperty dp)
        {
            BindingExpression expression = ((TextBox)(sender.FindName(controlName))).GetBindingExpression(dp);
            expression.UpdateSource();
            return expression;
        }


        //TEST
        protected void Test(object sender, RoutedEventArgs e)
        {
            var x = (ListBox)((Grid)sender).FindName("lvItems");
        }
    }
}
